<template>
  <div>
    <!-- 欢迎卡片 -->
    <el-card class="welcome-card" style="margin-bottom: 16px;">
      <div style="display: flex; align-items: center; padding: 16px;">
        <el-avatar :size="64" style="background-color: #409eff; margin-right: 16px;">
          <i class="el-icon-user-solid" style="font-size: 32px;"></i>
        </el-avatar>
        <div style="flex: 1;">
          <div style="font-size: 18px; font-weight: bold; margin-bottom: 4px; color: #303133;">欢迎回来，专家</div>
          <div style="font-size: 14px; color: #909399;">
            今天是 {{ currentDate }}，祝您工作愉快！
          </div>
        </div>
        <el-button
          type="text"
          style="color: #409eff;"
          @click="goToExpertHome"
        >
          查看询标结果
          <i class="el-icon-arrow-right" style="margin-left: 4px;"></i>
        </el-button>
      </div>
    </el-card>

    <el-card class="list-card" style="margin-bottom: 16px;">
      <div slot="header" style="display: flex; align-items: center; justify-content: space-between;">
        <span style="font-size: 18px; font-weight: bold;">询标列表</span>
        <el-input
          v-model="search"
          placeholder="编号搜索"
          style="width: 240px;"
          clearable
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>

      <el-table
        :data="filteredInquiries"
        v-loading="loading"
        element-loading-text="加载中..."
        style="width: 100%; margin-top: 16px;"
        stripe
        border
      >
        <el-table-column
          prop="ProjectNo"
          label="项目编号"
          sortable
          width="150"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              style="color: #409eff; font-weight: 500;"
              @click="sendInquiry(scope.row)"
            >
              {{ scope.row.ProjectNo }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column
          prop="ProjectName"
          label="项目名称"
          sortable
          min-width="200"
        ></el-table-column>

       

        <el-table-column
          prop="IsSend"
          label="是否已发起"
          sortable
          width="120"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.IsSend ? 'success' : 'warning'"
              size="small"
            >
              {{ scope.row.IsSend ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="120"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              plain
              @click="sendInquiry(scope.row)"
              :disabled="isButtonDisabled(scope.row)"
            >
              <i class="el-icon-s-promotion" style="margin-right: 4px;"></i>
              发起
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="display: flex; justify-content: flex-end; margin-top: 16px;">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-size="itemsPerPage"
          :total="totalItems"
          layout="total, prev, pager, next, jumper"
          background
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { GetExpertInquiryPage } from '@/api/BidderInquiry';
import Cookies from 'js-cookie'

export default {
  name: 'ExpertInquiryList',
  data() {
    return {
      search: '',
      loading: false,
      page: 1,
      itemsPerPage: 10,
      totalItems: 0,
      projectId: '',
      token: '',
      inquiries: []
    }
  },
  computed: {
    currentDate() {
      return new Date().toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      });
    },
    pageCount() {
      return Math.ceil(this.totalItems / this.itemsPerPage)
    },
    filteredInquiries() {
      if (!this.search) {
        return this.inquiries
      }
      const keyword = String(this.search || '').toLowerCase();
      return this.inquiries.filter(item => {
        const projectNo = item && item.ProjectNo != null ? String(item.ProjectNo).toLowerCase() : '';
        const projectName = item && item.ProjectName != null ? String(item.ProjectName).toLowerCase() : '';
        const inquiryContent = item && item.InquiryContent != null ? String(item.InquiryContent).toLowerCase() : '';
        return (
          projectNo.indexOf(keyword) !== -1 ||
          projectName.indexOf(keyword) !== -1 ||
          inquiryContent.indexOf(keyword) !== -1
        );
      })
    }
  },
  watch: {
    page() {
      this.fetchData()
    },
    itemsPerPage() {
      this.page = 1
      this.fetchData()
    }
  },
  mounted() {
    // 先初始化 token，再读取其他参数并请求数据
    this.initTokenFromUrl();
    // 获取其他参数 
    this.projectId = this.$route.query.projectId || '';
    console.log('专家询标列表 - projectId:', this.projectId);
    // 调用数据获取方法
    this.fetchData();
  },
  methods: {
    // 首次进入：从 URL 读取 token（兼容 token/Token/access_token），写入本地并清理 URL
    initTokenFromUrl() {  
       const q = this.$route.query || {};
       const urlToken = q.token || q.Token || q.access_token;
       if (urlToken) {
         try {
           localStorage.setItem('token', urlToken);
           sessionStorage.setItem('token', urlToken);
           Cookies.set('token',urlToken);  //这是什么页面，在这存的话，存之前拦截器获取不到，初始化页面   
           // 新增：将 token 写入 Cookie，默认 7 天过期
           console.log('专家询标列表 - 保存 token:', urlToken);
         } catch (e) {
           console.warn('保存 token 失败:', e);
         }
 
         const newQuery = { ...q };
         delete newQuery.token;
         delete newQuery.Token;
         delete newQuery.access_token;
         this.$router.replace({ path: this.$route.path, query: newQuery }).catch(() => {});
       } else {
         const storedToken = localStorage.getItem('token') || sessionStorage.getItem('token') || this.getCookie('token');
         if (storedToken) this.token = storedToken;
       }
     },

     // 新增：设置 Cookie
     setCookie(name, value, days) {
       var expires = '';
       if (days && !isNaN(days)) {
         var d = new Date();
         d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
         expires = '; expires=' + d.toUTCString();
       }
       document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
     },

     // 新增：读取 Cookie
     getCookie(name) {
       var pattern = new RegExp('(?:^|; )' + name.replace(/([.$?*|{}()\[\]\\/+^])/g, '\\$1') + '=([^;]*)');
       var match = document.cookie.match(pattern);
       return match ? decodeURIComponent(match[1]) : null;
     },
    goToExpertHome() {
      this.$router.push(`/expert/home?projectId=${this.projectId}`);
    },

    async fetchData() {
      this.loading = true;
      try {
        const params = {
          pageIndex: this.page,
          pageSize: this.itemsPerPage,
          key: this.search,
          projectId: this.projectId,
        };
        console.log('专家询标列表 - 请求参数:', params);
        
        const res = await GetExpertInquiryPage(params);
        console.log('专家询标列表 - 响应数据:', res);
        
        if (res && res.Data && res.Data.IsSuccess === false) {
          this.$message.error(res.Data.Message);
          return;
        }
        
        // 根据响应结构调整数据提取
        this.inquiries = (res && res.Data && res.Data.Data) || res || [];
        this.totalItems = (res && res.Data && res.Data.Count) || 0;
        
        console.log('专家询标列表 - 解析后数据:', {
          inquiries: this.inquiries,
          totalItems: this.totalItems
        });
        
      } catch (error) {
        console.error('获取专家询标列表失败:', error);
      } finally {
        this.loading = false;
      }
    },

    isButtonDisabled(item) {
      return item.IsSend === true;
    },

    sendInquiry(item) {
      this.$router.push({
        path: '/expert',
        query: { Id: item.Id }
      });
    },

    handleCurrentChange(currentPage) {
      this.page = currentPage;
      this.fetchData();
    }
  }
}
</script>

<style scoped>
.welcome-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.welcome-card >>> .el-card__body {
  padding: 0;
}

.list-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

.el-button--text {
  padding: 0;
  border: none;
  background: none;
}

.el-button--text:hover {
  background: none;
  color: #66b1ff;
}

.el-tag {
  border-radius: 4px;
}

.el-pagination {
  margin-top: 16px;
}

/* 卡片悬停效果 */
.el-card {
  transition: all 0.3s ease;
}

.el-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

/* 表格行悬停效果 */
.el-table__row:hover {
  background-color: #f5f7fa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-card div[style*="padding: 16px"] {
    flex-direction: column;
    text-align: center;
  }
  
  .welcome-card .el-avatar {
    margin-bottom: 16px;
    margin-right: 0;
  }
}
</style>